package core.base.exception;

import java.util.Map;
import java.util.TreeMap;

import core.util.MacroVariableInterpreter;
import core.util.MapMacroVariableContainer;

public class AppBizException extends Exception {

	private static final long serialVersionUID = 5474844251052375730L;
	private String code;
	private Object[] args;
	private String textMessage;

	public AppBizException() {
	}

	private static String formatMessage(String msg, Object[] args) {
		if (args == null) {
			return msg;
		}
		Map<String, Object> map = new TreeMap<String, Object>();
		for (int i = 0; i < args.length; i++) {
			map.put(String.valueOf(i), args[i]);
		}

		MapMacroVariableContainer mvc = new MapMacroVariableContainer(map);
		return MacroVariableInterpreter.interpret(msg, "{", "}", mvc);
	}

	public AppBizException(String code, String msg) {
		super(code + ": " + msg);
		this.code = code;
	}

	public AppBizException(String code, String msg, Throwable cause) {
		super(code + ": " + msg, cause);
		this.code = code;
	}

	public AppBizException(String code, Object[] args, String msg) {
		super(code + ": " + formatMessage(msg, args));
		this.code = code;
		this.args = args;
	}

	public AppBizException(String code, Object[] args, String msg, Throwable cause) {
		super(code + ": " + formatMessage(msg, args), cause);
		this.code = code;
		this.args = args;
	}

	public AppBizException(String code, String msg, Object... args) {
		super(code + ": " + formatMessage(msg, args));
		this.code = code;
		this.args = args;
	}

	public AppBizException(String code, Throwable cause, String msg, Object... args) {
		super(code + ": " + formatMessage(msg, args), cause);
		this.code = code;
		this.args = args;
	}

	public AppBizException(Throwable cause) {
		super(cause);
	}

	public String getCode() {
		return code;
	}

	public void setCode(String string) {
		code = string;
	}

	public Object[] getArgs() {
		return args;
	}

	public void setArgs(Object[] objects) {
		args = objects;
	}

	public String getTextMessage() {
		return textMessage;
	}

	public void setTextMessage(String textMessage) {
		this.textMessage = textMessage;
	}
}
